//
//  LPHUnlockView.m
//  手势解锁完整
//
//  Created by Mac on 15/12/19.
//  Copyright © 2015年 Mac. All rights reserved.
//

#import "LPHUnlockView.h"

@interface LPHUnlockView()

//保存按钮
@property(nonatomic,strong)NSArray * buttos;

//保存所有触摸过的按钮
@property(nonatomic,strong)NSMutableArray * selectedButtons;

//线条颜色
@property(nonatomic,strong)UIColor * linColor;

//记录当前触摸点
@property(nonatomic,assign)CGPoint current_point;

@end


@implementation LPHUnlockView

#pragma mark - 懒加载触摸过的按钮

-(NSMutableArray *)selectedButtons{
 
    if (_selectedButtons==nil) {
        
        _selectedButtons=[NSMutableArray array];
        
    }
    
    return _selectedButtons;
    
}

#pragma mark - 懒加载颜色线条

-(UIColor *)linColor{

    if (_linColor==nil) {
        
        _linColor=[UIColor colorWithRed:0/255.0 green:149/255.0 blue:255/255.0 alpha:1.0];
        
    }
    return _linColor;

}


#pragma mark - 懒加载按钮
-(NSArray *)buttos{

    
    if (_buttos==nil) {
        
        NSMutableArray * arrM =[NSMutableArray array];
        
        for (int i = 0; i<9; i++) {
            
            UIButton * btn =[[UIButton alloc]init];
            
            btn.tag=i;
            
            //不允许用户交互
            
            btn.userInteractionEnabled=NO;
            
            //设置各种按钮图片
            
            [btn setBackgroundImage:[UIImage imageNamed:@"gesture_node_normal"] forState:UIControlStateNormal];
            
            [btn setBackgroundImage:[UIImage imageNamed:@"gesture_node_highlighted"] forState:UIControlStateSelected];
            
            [btn setBackgroundImage:[UIImage imageNamed:@"gesture_node_error"]forState:UIControlStateDisabled];
            
            [self addSubview:btn];
            
            [arrM addObject:btn];
            
        }
        
        _buttos=arrM.copy;
        
        
    }
    
    return _buttos;

}

#pragma mark - 设置各个自控家frame 

- (void)layoutSubviews{

    [super layoutSubviews];
    
    CGFloat buttonW=74;
    CGFloat buttonH=buttonW;
    
    //列数
    int col =3;
    
    //间距
    CGFloat magin =(self.bounds.size.width - col*buttonW) / (col-1);
    
    for (int i  = 0; i<self.buttos.count; i++) {
        
        UIButton * button =self.buttos[i];
        
        int row_idx =i/col;
        int col_idx =i%col;
        
        CGFloat buttonX=col_idx * (magin + buttonW);
        CGFloat buttonY=row_idx * (magin + buttonH);
        
        //设置frame
        
        button.frame =CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
    }


}

#pragma mark - 点击事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    //获取当前按下点
    UITouch * toch =touches.anyObject;

    CGPoint loc =[toch locationInView:toch.view];
    
    for (UIButton* button in self.buttos) {
        
        if (CGRectContainsPoint(button.frame, loc) && !button.isSelected) {
            
            [self.selectedButtons addObject:button];
            
            button.selected=YES;
            
            break;
            
        }
        
    }
    
    
    

}

#pragma mark - 正在触摸事件
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    //获取当前按下点
    UITouch * toch =touches.anyObject;
    
    CGPoint loc =[toch locationInView:toch.view];
    
    self.current_point=loc;// 记录当前的触摸点
    
    for (UIButton* button in self.buttos) {
        
        if (CGRectContainsPoint(button.frame, loc) && !button.isSelected) {
            
             [self.selectedButtons addObject:button];
            
            button.selected=YES;
            
            break;
            
        }
        
    }

    //重绘
    
    [self setNeedsDisplay];

}


#pragma mark - 手指抬起事件
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    //防止出错后无法让Currcent——point 变成按钮一个中心点

    self.current_point=[[self.selectedButtons lastObject]center];
    
    //获取用户密码
    
    NSMutableString * passWord =[NSMutableString string];
    
    for (UIButton*button in self.selectedButtons) {
        
        [passWord appendFormat:@"%@",@(button.tag)];
        
        
    }
    
    BOOL isOK = NO;
    //判断密码是否正确
    
    if ([self.delegate respondsToSelector:@selector(unlockViewPassWord:andPassWord:)]) {
        
       isOK = [self.delegate unlockViewPassWord:self andPassWord:passWord];
        
    }
    
    
    if (isOK) {
        
        [self clearLockView];
        
    }else{
    
        
        
        self.linColor=[UIColor redColor];
        
        //禁止交互
       self.userInteractionEnabled=NO;
        
        //设置所有按钮为disabled
        
        for (UIButton * button in self.selectedButtons) {
            
            button.selected=NO;
            button.enabled=NO;
            
        }
    
        
        [self setNeedsDisplay];
        
        
        //1.0秒后消失
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self clearLockView];
            
            self.userInteractionEnabled=YES;
            
            
        });
        
    
    }
    
    
    

}

#pragma mark - 让unlock回到默认状态
- (void)clearLockView{

    //把所有按钮都变成no
    for (UIButton * button in self.selectedButtons) {
        
        button.selected=NO;
        button.enabled=YES;
        
    }
    
    //线条为空

    self.linColor=nil;
    //删除所有状态
    [self.selectedButtons removeAllObjects];
    
    
    [self setNeedsDisplay];
    

}



// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    
    //如果没有按钮就不用绘图
    if (self.selectedButtons.count == 0)return;
    
    //获取上下文
    CGContextRef ctx =UIGraphicsGetCurrentContext();
    
    //绘制路径
    
    UIBezierPath * path =[UIBezierPath bezierPath];
    
    for (int i  = 0; i < self.selectedButtons.count; i++) {
        
        UIButton * button =self.selectedButtons[i];
        
        if (i == 0) {
            
            [path moveToPoint:button.center];
            
        }else{
        
            [path addLineToPoint:button.center];
        
        }
    }
        [path addLineToPoint:self.current_point];
        
        
        //把路径添加到上下文
        CGContextAddPath(ctx, path.CGPath);
        
        //设置颜色
        [self.linColor set];
        
        //渲染
        
        CGContextDrawPath(ctx, kCGPathStroke);
        
    
    
}

@end
